package com.roncoo.education.api;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.ProductRequest;
import com.roncoo.education.api.response.ProductResponse;
import com.roncoo.education.db.entity.Product;
import com.roncoo.education.db.service.ProductService;
import com.roncoo.education.util.MyJwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ProductAdminController {

    @Resource
    private ProductService productService;

    @Resource
    MyJwtUtil myJwtUtil;

    @PostMapping("/saveProds")
    public String saveProduct(@Valid @RequestBody ProductRequest req, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long adminId = myJwtUtil.getUsernameFromToken(token);
        Map<String,String> ret= productService.saveProduct(adminId,req);
        return JSONUtil.toJsonStr(ret);
    }

    @PostMapping("/getProdPage")
    public String getProdPage(@Valid @RequestBody ProductRequest req){
        PageInfo<Product> pageInfo = productService.getProdPages(req);
        return JSONUtil.toJsonStr(pageInfo);
    }

    @GetMapping("/getProd")
    public String getProdDetail(Long id){
        ProductResponse news = productService.getProductById(id);
        return JSONUtil.toJsonStr(news);
    }

    @GetMapping("/deleteProd")
    public String deleteProd(Long id){
        productService.deleteProduct(id);
        return "ok";
    }

    @PostMapping("/setDelProd")
    public String setDelNewsComment(Long id){
        //逻辑下架
        productService.setDelFlag(id);
        return "ok";
    }


}
